from . import passport_blu
from flask import render_template, request, jsonify, session, make_response

from models import db
from models.index import Category, User


# 注册
@passport_blu.route("/registered")
def registered():
    return render_template("registered.htm")


# 注册
@passport_blu.route("/passport/registered", methods=["POST"])
def registered_detail():
    # # 1.提取数据
    mobile = request.json.get("mobile")
    nick_name = request.json.get("nick_name")
    password = request.json.get("password")
    email = request.json.get("email")
    image_code = request.json.get("image_code")
    print(mobile, nick_name, password, email, image_code)
    # 2.1 先查询是否已经有这个用户.
    if db.session.query(User).filter(User.nick_name == nick_name or User.mobile == mobile).first():
        return jsonify({
            "errno": 1001,
            "errmsg": "已经注册..."

        })

    # 2.2 注册用户
    # 将新用户的数据插入到数据库
    user = User()
    user.mobile = mobile
    user.nick_name = nick_name
    user.password = password
    user.email = email
    user.image_code = image_code

    try:
        db.session.add(user)
        db.session.commit()
        ret = {
            "errno": 0,
            "errmsg": "注册成功..."
        }
    except Exception as error:
        print("---->", error)
        db.session.rollback()
        ret = {
            "errno": 1002,
            "errmsg": "注册失败..."
        }

    return jsonify(ret)


# 登录
@passport_blu.route("/login")
def login():
    return render_template("login.htm")


@passport_blu.route("/passport/login", methods=["GET", "POST"])
def login_detail():
    # 1.提取登录时的用户名，密码
    nick_name = request.json.get("nick_name")
    password = request.json.get("password")

    # 2. 查询，如果存在表示登录成功，否则失败
    user = db.session.query(User).filter(User.nick_name == nick_name, User.password == password).first()
    if user:
        ret = {
            "errno": 0,
            "errmsg": "登录成功"
        }
        session['user_id'] = user.id
        session['nick_name'] = nick_name

    else:
        ret = {
            "errno": 2001,
            "errmsg": "用户名或者密码错误"
        }

    return jsonify(ret)




